import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

// 引入FastDFS客户端库
import * as FastDFS from 'fastdfs-client';

@Injectable()
export class FastDFSService {
  private client: any;

  constructor(private ConfigService: ConfigService) {
    this.client = new FastDFS({
      // tracker servers
      trackers: [
        {
          host: ConfigService.get('fastdfs.host'),
          port: ConfigService.get('fastdfs.port'),
        },
      ],
      // 默认超时时间10s
      timeout: 10000,
      // 默认后缀
      // 当获取不到文件后缀时使用
      defaultExt: 'txt',
      // charset默认utf8
      charset: 'utf8',
    });
  }

  // 上传文件
  async uploadFile(file: any): Promise<string> {
    // 初始化上传参数
    const options = {
      meta: {}, // 如果有元数据可以在这里设置
      ext: 'jpg', // 文件后缀
    };
    const originalname = file.originalname;
    const ext = originalname.split('.').pop();
    options.ext = ext;
    const buffer = file.buffer;

    try {
      // 上传文件至FastDFS
      return await this.client.upload(buffer, options);
    } catch (error) {
      console.error('Error uploading to FastDFS:', error);
      throw error;
    }
  }

  // 删除文件
  deleteFile(fileId: string) {
    this.client.del(fileId);
  }
}
